﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TVGuide.DataAccess;
using TVGuide.DataAccess.Repository;
using TVGuide.DataAccess.Common;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Net;
using System.IO;
using System.Collections.Specialized;
using System.Net.Mail;

namespace TVGuide.Parser
{
    public class MainProgram
    {
        public static ProgramRepository pr = ProgramRepository.Instance();
        public static void UcomParseForWeek()
        {
            DateTime start = DateTime.Now;
            
            for (int i = 0; i < 7; i++)
            {
                List<Program> ucomPrList = UCOMParseEngine.ParseAll((DateTime)DateTime.Today.AddDays(i));

                if (ucomPrList.Count != 0)
                {
                    TVGuide.DataAccess.Utilsities.addPrograms(ucomPrList);
                }

            }
            Console.Write("Time elapsed " + (DateTime.Now.Minute - start.Minute) + " minutes.");
        }

        public static void EterParseForWeek()
        {
            DateTime start = DateTime.Now;

            for (int i = 0; i <= 7 - (int)DateTime.Today.DayOfWeek; i++)
            {
                List<Program> eterPrList = EterParserEngine.ParseAll((DateTime)DateTime.Today.AddDays(i));

                if (eterPrList.Count != 0)
                {
                    TVGuide.DataAccess.Utilsities.addOverwriteProgramms(eterPrList);
                }

            }
            Console.Write("Time elapsed " + (DateTime.Now.Minute - start.Minute) + " minutes.");
        }

        public static void NTVParseForWeek()
        {
            for (int i = 0; i < 7; i++)
            {
                List<Program> ntvPrList = NTVPlusParseEngine.ParseAll(DateTime.Today.AddDays(i)).Distinct().ToList();
                TVGuide.DataAccess.Utilsities.addOverwriteProgramms(ntvPrList);


            }

        }

        public static void ParseForWeek()
        {
            var parsers = Parsers.ParsersList;
            foreach (var parser in parsers)
            {
                var programsList = parser.ParseProgramForWeek();
                if (programsList.Count != 0)
                {
                    TVGuide.DataAccess.Utilsities.addOverwriteProgramms(programsList);
                }
            }
        }

        public static void EterParse()
        {
            EterParserEngine.ParseAll(DateTime.Today);
        }

        public static List<string> GetSopcastUrls(string href){
            //href = "http://gooool.org/online/37482-chelsi-vest-hem-smotret-onlayn-pryamaya-video-translyaciya.html";
            List<string> urls = new List<string>();
            string content = HTTPClient.GetSiteContent(href);
            string patt = "<strong><a href=\"(.*?)\"><span[^>]*>(\\d+)</span>(.*?)</strong>";
            Regex rgx = new Regex(patt, RegexOptions.IgnoreCase);
            MatchCollection matches = rgx.Matches(content);
            string sopcastUrl = "";
            string sopcastId = "";
            string info = "";
            foreach (Match m in matches)
            {
                sopcastUrl = m.Groups[1].Value;
                sopcastId = m.Groups[2].Value;
                info = TVGuide.Common.Utils.removeHTMLTags(m.Groups[3].Value).Trim();
                urls.Add(sopcastUrl);
            }


            return urls;
        }

        static void Main(string[] args)
        {

        }

        public static void ParseTorrentTV()
        {

            string formUrl = "http://torrent-tv.ru/auth.php"; // NOTE: This is the URL the form POSTs to, not the URL of the form (you can find this in the "action" attribute of the HTML's form tag
            string formParams = string.Format("email={0}&password={1}&enter=", "noramirkh@gmail.com", "NoraM1986");
            string cookieHeader;
            WebRequest req = WebRequest.Create(formUrl);
            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";
            byte[] bytes = Encoding.ASCII.GetBytes(formParams);
            req.ContentLength = bytes.Length;
            using (Stream os = req.GetRequestStream())
            {
                os.Write(bytes, 0, bytes.Length);
            }
            WebResponse resp = req.GetResponse();
            cookieHeader = resp.Headers["Set-cookie"];
            string pageSource;
            string contentId = "";
            Regex rgxRemoveBullshit = new Regex("[\r\n]");

            string contentIDRgx = "loadPlayer\\(\"(.*?)\",";
            Regex rgx = new Regex(contentIDRgx, RegexOptions.IgnoreCase);

            // Get channels from DB, which have torrentChannelID not NULL, get contentID and save it to DB 
            var channals = TVGuide.DataAccess.Utilsities.getChannelsWithTorrentTV();
            string messageBody = "Chanells that have new content IDs \n\n";
            bool updated = false;
            foreach (channel c in channals )
            {
                int? torrentChannelID = c.torrentChannelID;
                string getUrl = "http://torrent-tv.ru/torrent-online.php?translation=" + torrentChannelID;
                WebRequest getRequest = WebRequest.Create(getUrl);
                getRequest.Headers.Add("Cookie", cookieHeader);
                WebResponse getResponse = getRequest.GetResponse();
                using (StreamReader sr = new StreamReader(getResponse.GetResponseStream()))
                {
                    pageSource = sr.ReadToEnd();
                    // Get content ID
                    pageSource = (rgxRemoveBullshit.Replace(pageSource, "")).Replace('\t', ' ').Replace("&ndash;", "-").Replace("&nbsp;", " ");
                    Match match = rgx.Match(pageSource);
                    if (match.Success)
                    {
                        contentId = match.Groups[1].Value;
                        //Add to database
                        if (c.torrentContentID!=contentId)
                        {
                            updated = true;
                            TVGuide.DataAccess.Utilsities.setChannelTorrentTVContentID(torrentChannelID, contentId);
                            messageBody += c.displayName + "\n";
                        }

                    }

                    
                }
            }

            if (updated)
            {
                var message = new MailMessage("info@tvcuyc.com", "noramirkh@gmail.com");
                message.Body = messageBody;
                message.Subject = "Torrent streams updated";
                var client = new SmtpClient();
                client.EnableSsl = false;
                client.Send(message);
            }

        }
    
        public static void GetSopastURL(string url1)
        {

            string url = "http://gooool.org/news/angliyathe_fa_premier_league/";
            string content = HTTPClient.GetSiteContent(url, Encoding.GetEncoding(1251), "Gooool.org");
            string tablePatt = "<table.*style=\"color:yellow\".*?</table>";
            Regex rgx = new Regex(tablePatt, RegexOptions.IgnoreCase);
            Match match = rgx.Match(content);
            string date = "";
            string time = "";
            string name = "";
            string href = "";
            List<string> sopcastURLs = new List<string>();
            if (match.Success)
            {
                string gamesTabe = match.Value;
                string tdPatt = "<td.*?<a href=\"(.*?)\".*?</td>";
                string timePatt = @"(\d\d:\d\d)\s*(.*)";
                Regex tdReg = new Regex(tdPatt, RegexOptions.IgnoreCase);
                Regex timeReg = new Regex(timePatt, RegexOptions.IgnoreCase);
                MatchCollection matches = tdReg.Matches(gamesTabe);
                bool first = true;
                foreach (Match m in matches)
                {
                    string htmlStr = m.Value;
                    string s = TVGuide.Common.Utils.removeHTMLTags(htmlStr).Trim();
                    if (first)
                    {
                        date = s.Substring(0, s.IndexOf(':')-2).Trim();
                        first = false;
                    }

                    time = timeReg.Match(s).Groups[1].Value;
                    name = timeReg.Match(s).Groups[2].Value;
                    href = m.Groups[1].Value;
                    sopcastURLs = GetSopcastUrls(href);

                }

            }
            
            Console.ReadLine();
        }

        public static void ParseNewUcomFromFile(string filePath)
        {
            List<Program> newUcom = UCOMParseEngineNew.ParseSpecificProgramFromFile(filePath);
            TVGuide.DataAccess.Utilsities.addOverwriteProgramms(newUcom);
        }
    }


}
